public class Solution99 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    TreeNode first=null,second=null,last=null;

    public void recoverTree(TreeNode root) {
        dfs(root);
        if (second==null){
            second=last;
        }
        int temp=first.val;
        first.val=second.val;
        second.val=temp;
    }

    private void dfs(TreeNode root) {
        if (root.left!=null){
            dfs(root.left);
        }
        if (last!=null && root.val<last.val){
            if (first==null){
                first=last;
            }
        }
        if (first!=null && second==null && root.val>first.val){
            second=last;
        }
        last=root;
        if (root.right!=null){
            dfs(root.right);
        }
    }

    public static void main(String[] args) {
        TreeNode treeNode=new TreeNode(5,new TreeNode(3,new TreeNode(-1),new TreeNode(2)),new TreeNode(9));
        new Solution99().recoverTree(treeNode);
        System.out.println(treeNode.val);
    }
}
